package com.xiaoyao.login.config;

import com.xiaoyao.login.filter.JWTFilter;
import com.xiaoyao.login.handle.CustomAuthenticationSuccessHandler;
import com.xiaoyao.login.handle.CustomLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CustomSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
    @Resource
    private CustomLogoutSuccessHandler customLogoutSuccessHandler;
    @Resource
    private JWTProvider jwtProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)  // 设置无状态
                .and()
                .authorizeRequests()  // 配置请求权限
                .antMatchers("/**").hasRole("ADMIN") // 需要角色
                .anyRequest().authenticated() // 所有的请求都需要登录
                .and()
                // 配置登录url，和登录成功处理器
                .formLogin().loginProcessingUrl("/login").successHandler(customAuthenticationSuccessHandler)
                // 取消csrf防护（跨站请求伪造攻击）
                .and().csrf().disable()
                .httpBasic()
                // 配置登出url，和登出成功处理器
                .and().logout().logoutUrl("/logout").logoutSuccessHandler(customLogoutSuccessHandler)
                // 在UsernamePasswordAuthenticationFilter之前执行我们添加的JWTFilter
                .and().addFilterBefore(new JWTFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 添加不做权限的URL
        web.ignoring()
                .antMatchers("/main")
                .antMatchers("/static/**")
                .antMatchers("/dict/**");
    }

    public PasswordEncoder passwordEncoder(){
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}
